//var logger = require('../log').logger;
//var TempLimitInfo = require('../mock/baseInfo').TempLimitInfo;
var fs = require("fs");
var configData = eval("(" + fs.readFileSync("./config/properties.json", "utf-8")+ ")");
var crc = require('crc');
var TYPE = 0x11;
var LOCAL_IP = configData.udpServerIP;
var SOURCE_TRAM_CS = 0x04;
var logger = require('../log').logger;

//创建车地注册包
exports.createTramRegister = function(tramData){
	var message = new Buffer(8);
	//数据源设备号
	message.writeUInt8(SOURCE_TRAM_CS,0);
	//数据类型
	message.writeUInt8(0x51,1);
	//长度
	message.writeUInt16LE(4,2);
	//车载通信协议版本
	message.writeUInt32LE(1,4);
	var headPacket = createHeadBuffer(tramData, TYPE, message.length, LOCAL_IP );
	return 	createCompletedBuffer(headPacket,message);
};

//创建车地应答信息包
exports.createTramReply = function(tramData){
	var message = new Buffer(8);
	//数据源设备号
	message.writeUInt8(SOURCE_TRAM_CS,0);
	//数据类型
	message.writeUInt8(0x60,1);
	//长度
	message.writeUInt16LE(4,2);
	//应答数据类型
	/*对于其数据类型具体含义未知*/
	message.writeUInt16LE(tramData.dataType,4);
	//应答序号
	message.writeUInt16LE(tramData.orderNum,6);
	var headPacket = createHeadBuffer(tramData, TYPE, message.length, LOCAL_IP );
	return 	createCompletedBuffer(headPacket,message);
};

exports.createTramStatus = function(tramData){
	var message = new Buffer(48);
	message.writeUInt8(SOURCE_TRAM_CS,0);
	message.writeUInt8(0x04,1);
	message.writeUInt16LE(44,2);
	var date = new Date();
	
	//year
	message.writeUInt8(date.getFullYear().toString().slice(2),4);
	//month
	message.writeUInt8(date.getMonth()+1,5);
	//day
	message.writeUInt8(date.getDate(),6);
	//hour
	message.writeUInt8(date.getHours(),7);
	//min
	message.writeUInt8(date.getMinutes(),8);
	//sec
	message.writeUInt8(date.getSeconds(),9);
	//speed
	message.writeUInt8(tramData.speed||0,10);
	//limitSpeed
	message.writeUInt8(80,11);

	message.writeUInt16LE(tramData.distance||0,12);
	message.writeUInt32LE(tramData.totalLength||0,14);
	message.writeUInt32LE(tramData.totalLength||0,18);
	//var tempArr = [0x01FF, 0x0033, 0x0044];
	//var randomIndex = Math.floor(Math.random()*3);
	message.writeUInt16LE(0x7F,22);
	message.writeUInt16LE(0x7F,24);
	message.writeUInt8(0xA,26);
	message.writeUInt8(tramData.lineCode,27);
	message.writeUInt16LE(tramData.fromTerminus,28);
	message.writeUInt16LE(tramData.toTerminus,30);
	if(tramData.direct === 'down'){
		message.writeUInt8(1,32);
	}else{
		message.writeUInt8(2,32);
	}
	message.writeUInt32LE(tramData.serviceNum,33);
	message.write("3000",37,4,'ascii');
	message.writeUInt8(0x1F,41);
	if(tramData.direct === 'down'){
		message.writeUInt8(0x04,42);
	}else{
		message.writeUInt8(0x08,42);
	}
	
	message.writeUInt8(tramData.driveMode,43);
	message.writeUInt8(tramData.isReached,44);
	message.writeUInt16LE(0,45);
	message.writeUInt8(0,47);
	var headPacket = createHeadBuffer(tramData, TYPE, message.length,  LOCAL_IP );
	return 	createCompletedBuffer(headPacket,message);
};
exports.createGPSInfo = function(data){
	var message = new Buffer(24);
	message.writeUInt8(SOURCE_TRAM_CS,0);
	message.writeUInt8(0x30,1);
	message.writeUInt16LE(20,2);
	//信息来源
	message.writeUInt8(1,4);
	//GPS/BD有效卫星数
	message.writeUInt8(0,5);
	//GPS方向
	message.writeUInt16LE(0,6);
	//GPS速度
	message.writeUInt16LE(0,8);
	//GPS高度
	message.writeUInt16LE(0,10);
	//GPS半球标志
	message.write("E",12,1,'ascii');
	//GPS半球标志
	message.write("N",13,1,'ascii');
	//GPS经度的整数部分
	message.writeUInt8(data.longitudeInt,14);
	//GPS经度的小数部分
    message.writeUInt32LE(data.longitudeDee,15);
	//GPS纬度的整数部分
    message.writeUInt8(data.latitudeInt,19);
	//GPS纬度的小数部分
   message.writeUInt32LE(data.latitudeDee,20);
	var headPacket = createHeadBuffer(data, TYPE, message.length,  LOCAL_IP);
	return 	createCompletedBuffer(headPacket,message);

}
exports.createRunArgs = function( tramData){
	var startBuffer = new Buffer(16);
	startBuffer.writeUInt8(SOURCE_TRAM_CS,0);
	startBuffer.writeUInt8(0x06,1);
	startBuffer.writeUInt16LE(12,2);
	startBuffer.writeUInt16LE(tramData.packetNum,4);
	startBuffer.write(tramData.driverNum.toString(),6,4,'ascii');
	startBuffer.writeUInt16LE(0,14);
	var headPacket = createHeadBuffer(tramData, TYPE, startBuffer.length,  LOCAL_IP);
	return 	createCompletedBuffer(headPacket,startBuffer);
};
exports.createVersionInfo = function( tramData ){
	var message = new Buffer(40);
	message.writeUInt8(SOURCE_TRAM_CS,0);
	message.writeUInt8(0x02,1);
	message.writeUInt16LE(36,3);
	message.writeUInt32LE(1,5);
	message.writeUInt32LE(1,9);
	message.writeUInt32LE(1,13);
	message.writeUInt32LE(1,17);
	message.writeUInt32LE(1,21);
	message.writeUInt32LE(1,25);
	message.writeUInt32LE(1,29);
	message.writeUInt32LE(1,33);
	message.writeUInt32LE(1,37);
	var headPacket = createHeadBuffer(tramData, 0x11, message.length,  LOCAL_IP);
	return 	createCompletedBuffer(headPacket,message);
}
function createHeadBuffer( data, type, packetLen, ip ){
	if(isNaN(data.packetNum)||isNaN(packetLen)){
		return false;
	}
	var headPacket = new Buffer(16);
	headPacket.writeUInt16BE(0xAABB,0);
	headPacket.writeUInt8(1, 2);
	headPacket.writeUInt8(16 , 3);
	headPacket.writeUInt16LE(data.packetNum , 4);
	headPacket.writeUInt8(type,6);
	headPacket.writeUInt16LE(packetLen,7);
	//headPacket.write(data.tramCode.toString(),9,4,'ascii');
	headPacket.writeUInt32LE(data.tramCode,9);
	headPacket.writeUInt8(25,13);
	headPacket.writeUInt16LE(0,14);
	return headPacket;
}
function createCompletedBuffer(headPacket,message){
	var concatBuffer = Buffer.concat([headPacket,message],(headPacket.length+message.length));
	var crc16Buffer = new Buffer(2);
	crc16Buffer.writeUInt16LE(crc.crc16(concatBuffer),0);
	var finalBuffer = Buffer.concat([headPacket,message,crc16Buffer],(headPacket.length+message.length+crc16Buffer.length));
	return finalBuffer;
}
exports.splitBuffer = function(msg){
	var message = msg;
	var bufArr = [];
	var fixedLen = 22;
	while(message.length>0){
		var contentLen = message.readUInt16LE(18);
		console.log("****>>>>>>>>>>"+contentLen);
		var currentBuffer = message.slice(0,(fixedLen+contentLen));
		message = message.slice(fixedLen+contentLen);
		bufArr.push(currentBuffer);
	}
	//console.log(bufArr)
	return bufArr;
}
exports.getDataType = function(msg){
	var dataType = msg.readUInt8(17);
	return dataType;
}
 //接收中心发车请求相应 运行计划信息包
  exports.getOperationPlan = function ( msg ){
	  var obj = {};
	   //车次号
		obj['serviceNum'] = msg.readUInt32LE(22);
		 //司机号
		obj['driverNum'] = msg.toString('ascii',26,29);
	  //车辆编号
	    obj['tramCode'] =  msg.readUInt32LE(9);
		 //序号
		obj['orderNum'] = msg.readUInt16LE(20);
		
	  //  console.log(obj);
		return obj;
  }
	//接收时刻表包
	exports.getScheduleInfo = function(msg){
		var scheduleInfoObj = {};
		var scheduleArr = [];
		scheduleInfoObj['tramCode'] =  msg.toString('ascii',19,23);
		//长度
		var msgLen = msg.readUInt16LE(29);
		//序号
		scheduleInfoObj['orderNum'] = msg.readUInt16LE(31);
		//时刻表包数
		var scheduleNums = msg.readUInt8(33);
		scheduleInfoObj['scheduleNums'] = scheduleNums;
		//时刻表编号
		scheduleInfoObj['scheduleId'] = msg.readUInt8(34);
		//重复长度
		var repeatLen = 6;
		for(var i = 0; i < scheduleNums; i++){
			var schedule = {};
			//计划停站时间 秒
			schedule.planStopTime = msg.readUInt16LE(35+repeatLen*i);
			//计划到达时间  时
			schedule.planArriveHour = msg.readUInt8(37+repeatLen*i);
			//计划到达时间 分
			schedule.planArriveMin = msg.readUInt8(38+repeatLen*i);
			//计划到达时间 秒
			schedule.planArriveSec = msg.readUInt8(39+repeatLen*i);
			//车站号
			schedule.stationCode = msg.readUInt16BE(40+repeatLen*i);
			//console.log(schedule);
			scheduleArr.push(schedule);
		}
		scheduleInfoObj['schedules'] = scheduleArr;
		//console.log(scheduleInfoObj)
		return scheduleInfoObj;

	}
  //接收中心文本消息
  exports.getTextMsg = function( msg ){
	    var obj = {};
		obj['tramCode'] =  msg.toString('ascii',19,23);
	    var msgLen = msg.readUInt16LE(29);
		obj['text'] = msg.toString('utf8',33,31+msgLen);
		return obj;
   }
  //接收注册应答包
  exports.getReplyPacket = function( msg ){
	  var obj = {};
	   obj['tramCode'] =  msg.toString('ascii',19,23);
		//长度
	   obj['msgLen'] = msg.readUInt16LE(29);
	    //地面通信协议版本号
	   obj['protocolVersion'] = msg.readUInt8(31);
	    //注册标志
	   obj['registerFlag'] = msg.readUInt8(33);

	 //  console.log(obj);
	   return obj;
   }
	//接收中心应答包
	exports.getCenterReply = function(msg){
		var obj = {};
		obj['tramCode'] =  msg.toString('ascii',19,23);
		//长度
		var msgLen = msg.readUInt16LE(29);
		//应答数据类型
		obj['replyType'] = msg.readUInt16LE(31);
		//应答序号
		obj['orderNum'] = msg.readUInt16LE(33);
		//console.log(obj);
		return obj;
	}
   //接收地面临时限速包
  exports.getLimitSpeedObj = function( msg ){
    //对应某辆车限速信息总包，返回
    var limitPacketObj = {};
	//存放多个多个限速段数组
	var limitSetArr = [];
    var UNITLENTH = 19;
    var tramCode =  msg.toString('ascii',19,23);
	limitPacketObj['tramCode'] = tramCode;
	//长度
    var msgLen = msg.readUInt16LE(29);
    //序号
    var orderNum = msg.readUInt16LE(31);
    //限速数量
  	var limitQuantity = msg.readUInt8(33);
	  for( var i = 0; i < limitQuantity; i++){
			//临时限速编号
			var tempLimitNum = msg.readUInt16LE(34 + UNITLENTH*i);
			//调度命令号
			var dispatchOrderNum = msg.readUInt16LE(36 + UNITLENTH*i);
			//线路号
			var lineCode = msg.readUInt8(38 + UNITLENTH*i);
			//上下行 0 上行 1 下行
			var downUpType = msg.readUInt8(39 + UNITLENTH*i)==0?"up":"down";

			//车站代号
			var stationCode = msg.readUInt16BE(40 + UNITLENTH*i);
			//距离
			var distance = msg.readUInt16LE(42 + UNITLENTH*i);
			//限速值
			var limitValue = msg.readUInt8(44 + UNITLENTH*i);
			//限速区段长度
			var limitSectionDistance = msg.readUInt16LE(45+ UNITLENTH*i);
			var beginHour = msg.readUInt8(47 + UNITLENTH*i);
			var beginMin = msg.readUInt8(48+ UNITLENTH*i);
			var beginSec = msg.readUInt8(49 + UNITLENTH*i);
			var endHour = msg.readUInt8(50 + UNITLENTH*i);
			var endMin = msg.readUInt8(51 + UNITLENTH*i);
			var endSec = msg.readUInt8(52 + UNITLENTH*i);
			var tempLimitInfo = new TempLimitInfo(orderNum, limitQuantity, tempLimitNum, dispatchOrderNum, lineCode, downUpType, stationCode, distance, limitValue, limitSectionDistance, beginHour, beginMin, beginSec, endHour, endMin, endSec);
			limitSetArr.push(tempLimitInfo);
    }
    limitPacketObj['tempLimitInfo'] = limitSetArr;
    return limitPacketObj;
   }